package com.sx.mvvmlibs.base.impl

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import androidx.viewbinding.ViewBinding
import com.sx.mvvmlibs.base.BaseApp
import com.sx.mvvmlibs.base.BaseModel
import com.sx.mvvmlibs.base.BaseViewModel
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type

/**
 * @Author: YY
 * @Date: 2022/1/8
 * @Describe: View层
 */
interface IView<V : ViewBinding, VM: BaseViewModel<out BaseModel>> {

    /**
     * 初始化界面传递参数
     */
    fun initParam() {}

    /**
     * 初始化 DataBinding
     */
    fun initBinding(inflater: LayoutInflater, container: ViewGroup?): V

    /**
     * 初始化监听事件
     */
    fun initListener(){}

    /**
     * 初始化ViewModel
     */
    fun initViewModel()

    /**
     * 初始化数据
     */
    fun initData()

    /**
     * 初始化数据 Bundle
     */
    fun initData(bundle: Bundle?){}

    /**
     * 初始化界面观察者的监听
     */
    fun initViewObservable(){}

    /**
     * 初始化通用的 UI 改变事件，基类应该在初始化后设为 final
     */
    fun initUIChangeLiveData()


    /**
     * 创建ViewModel
     */
    @Suppress("UNCHECKED_CAST")
    fun createViewModel(viewModelStoreOwner: ViewModelStoreOwner): VM {
        var modelClass: Class<VM>?
        val type: Type? = javaClass.genericSuperclass
        modelClass = if (type is ParameterizedType) {
            type.actualTypeArguments[1] as Class<VM>
        } else {
            null
        }
        if (modelClass == null) {
            modelClass = BaseViewModel::class.java as Class<VM>
        }
        //如果没有指定泛型参数，则默认使用BaseViewModel
        BaseViewModel::class.java
        return ViewModelProvider(viewModelStoreOwner,
            ViewModelProvider.AndroidViewModelFactory(BaseApp.getInstance()))[modelClass]
    }
}